// DlgEditSource.cpp : implementation file
//

#include "stdafx.h"
#include "Celsus.h"
#include "DlgListSource.h"
#include "DlgEditSource.h"

// CDlgListSource dialog

IMPLEMENT_DYNAMIC(CDlgListSource, CDialog)

CDlgListSource::CDlgListSource(CWnd* pParent /*=NULL*/)
	: CDialog(CDlgListSource::IDD, pParent)
	, m_szFind(_T(""))
{
	m_bSortAscending = TRUE;
	m_nCurrentSort = 0;
	m_nCurrentRecord = -1;
	m_nStaffID = -1;
}

CDlgListSource::~CDlgListSource()
{
}

void CDlgListSource::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_LINKS, m_ctrlLinksList);
	DDX_Text(pDX, IDC_EDIT_FIND, m_szFind);
}


BEGIN_MESSAGE_MAP(CDlgListSource, CDialog)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_LINKS, &CDlgListSource::OnLvnItemchangedListLinks)
	ON_NOTIFY(LVN_GETDISPINFO, IDC_LIST_LINKS, &CDlgListSource::OnLvnGetdispinfoListLinks)
	ON_NOTIFY(HDN_ITEMCLICK, 0, &CDlgListSource::OnHdnItemclickListLinks)
	ON_NOTIFY(LVN_ODFINDITEM, IDC_LIST_LINKS, &CDlgListSource::OnLvnOdfinditemListLinks)
	ON_NOTIFY(NM_DBLCLK, IDC_LIST_LINKS, &CDlgListSource::OnNMDblclkListLinks)
	ON_BN_CLICKED(IDC_BUTTON_ADD, &CDlgListSource::OnBnClickedButtonAdd)
	ON_BN_CLICKED(IDC_BUTTON_UPDATE, &CDlgListSource::OnBnClickedButtonUpdate)
	ON_BN_CLICKED(IDC_BUTTON_EDIT, &CDlgListSource::OnBnClickedButtonEdit)
	ON_EN_CHANGE(IDC_EDIT_FIND, &CDlgListSource::OnEnChangeEditFind)
	ON_BN_CLICKED(IDC_BUTTON_FIND_SOURCE, &CDlgListSource::OnBnClickedButtonFindSource)
	ON_BN_CLICKED(IDC_BUTTON2, &CDlgListSource::OnBnClickedButton2)
END_MESSAGE_MAP()


// CDlgListSource message handlers

BOOL CDlgListSource::OnInitDialog()
{
	CDialog::OnInitDialog();

	ASSERT( m_nStaffID >= 0 );

	// set extended styles
	m_ctrlLinksList.SetExtendedStyle( LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_SUBITEMIMAGES | LVS_EX_INFOTIP  );
	// insert columns	
	m_ctrlLinksList.InsertColumn( SOURCE_DATE, _T("Date"), LVCFMT_LEFT,  120, SOURCE_DATE );
	m_ctrlLinksList.InsertColumn( SOURCE_TITLE, _T("Source"), LVCFMT_LEFT,  200, SOURCE_TITLE );
	m_ctrlLinksList.InsertColumn( SOURCE_URL, _T("Address"), LVCFMT_LEFT,  200, SOURCE_URL );

	// set sort
	m_szSort = _T("title");

	// disable edit button
	GetDlgItem( IDC_BUTTON_EDIT )->EnableWindow( FALSE );

	// fill list
	FillList();

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

void CDlgListSource::OnOK()
{
	// TODO: Add your specialized code here and/or call the base class

	CDialog::OnOK();
}

void CDlgListSource::OnCancel()
{
	// TODO: Add your specialized code here and/or call the base class

	CDialog::OnCancel();
}

void CDlgListSource::OnBnClickedButtonAdd()
{
	CDlgEditSource dlgSource;
	dlgSource.m_nStaffID = m_nStaffID;
	dlgSource.m_nItemID = -1;	
	dlgSource.m_bAdd = TRUE;
	// show dialog
	if( dlgSource.DoModal() == IDOK )
	{
		// fill list
		FillList( dlgSource.m_nItemID );
	}
}

void CDlgListSource::OnBnClickedButtonEdit()
{
	// get request
	ASSERT( m_nCurrentRecord <= m_aLinksList.GetCount() );

	CDlgEditSource dlgSource;
	dlgSource.m_nStaffID = m_nStaffID;
	dlgSource.m_nItemID = m_aLinksList.GetAt( m_nCurrentRecord ).m_id;
	// show dialog
	if( dlgSource.DoModal() == IDOK )
	{
		// fill list
		FillList();
	}
}

void CDlgListSource::OnBnClickedButtonUpdate()
{
	//// check to make sure
	//if( AfxMessageBox( _T("This will update Source Links from Item Links.\n\nDo you want to continue?"), MB_YESNO ) == IDNO )
	//	return;

	//CArray<REQUEST_LINK> Requests;
	//SOURCE_LINK Source;
	//CString szSourceTitle;

	//// get request links
	//appConfig.m_SQL.GetRequestLinkss( &Requests );

	//// loop through request links
	//for( LONG nIndex = 0; nIndex < Requests.GetCount(); nIndex++ )
	//{
	//	// get link sources
	//	szSourceTitle = Requests.GetAt( nIndex ).m_source.Left( Requests.GetAt( nIndex ).m_source.Find( appConfig.m_SFX.szSourceEndString ));

	//	// check souce
	//	if( appConfig.m_SQL.GetRowCount( CMySQLEx::source_links, _T("title"), szSourceTitle ) < 1 )
	//	{
	//		// inset source_link table
	//		Source.m_id = m_nStaffID;
	//		Source.m_date_in = COleDateTime::GetCurrentTime();
	//		Source.m_title = szSourceTitle;
	//		Source.m_link = Requests.GetAt( nIndex ).m_link;
	//		// set links
	//		appConfig.m_SQL.SetSourceLink( &Source );
	//	}
	//}
}

void CDlgListSource::OnBnClickedButton2()
{
	// update data
	UpdateData();
	// set filter
	m_szFilter.Empty();
	// fill list
	FillList();
}

void CDlgListSource::OnBnClickedButtonFindSource()
{
	// update data
	UpdateData();
	// set filter
	m_szFilter.Format( _T("(title LIKE '%%%s%%' OR link LIKE '%%%s%%')"), m_szFind, m_szFind );
	// fill list
	FillList();
}

void CDlgListSource::OnEnChangeEditFind()
{
	// set deafault
	SetDefaultButton( IDC_BUTTON_FIND_SOURCE );
}

void CDlgListSource::FillList(LONG nID)
{
	// clear lists
	m_aLinksList.RemoveAll();
	m_ctrlLinksList.DeleteAllItems();

	// get links
	appConfig.m_SQL.GetSourceLinks( &m_aLinksList, m_szFilter, m_szSort );

	// set item count
	m_ctrlLinksList.SetItemCountEx( m_aLinksList.GetCount(), LVSICF_NOINVALIDATEALL | LVSICF_NOSCROLL );

	// set column width
	m_ctrlLinksList.SetColumnWidth( SOURCE_DATE, LVSCW_AUTOSIZE );
	m_ctrlLinksList.SetColumnWidth( SOURCE_TITLE, LVSCW_AUTOSIZE );
	m_ctrlLinksList.SetColumnWidth( SOURCE_URL, LVSCW_AUTOSIZE );

	// check for added
	if( nID >= 0 )
	{
		for( LONG nIndex = 0; nIndex < m_aLinksList.GetCount(); nIndex++ )
		{	
			if( m_aLinksList.GetAt( nIndex ).m_id == nID )
				m_nCurrentRecord = nIndex;
		}
	}

	// set selection
	if( m_nCurrentRecord >= 0 )
	{
		m_ctrlLinksList.SetSelectionMark( m_nCurrentRecord );
		m_ctrlLinksList.SetItemState( m_nCurrentRecord, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED );
		m_ctrlLinksList.EnsureVisible( m_nCurrentRecord, FALSE );
	}
}

void CDlgListSource::OnLvnItemchangedListLinks(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);

	// get new selection
	if( pNMLV->uNewState & LVIS_SELECTED )
	{
		// set current record
		m_nCurrentRecord = pNMLV->iItem;
		// enable edit button
		GetDlgItem( IDC_BUTTON_EDIT )->EnableWindow();
		// set deafault
		SetDefaultButton( IDC_BUTTON_EDIT );
	}
	*pResult = 0;
}

void CDlgListSource::OnLvnGetdispinfoListLinks(NMHDR *pNMHDR, LRESULT *pResult)
{
	NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;

    // Create a pointer to the item
    LV_ITEM* pItem = &(pDispInfo)->item;

    // Which item number?
    INT nItemId = pItem->iItem;

	// get request
	ASSERT( nItemId <= m_aLinksList.GetCount() );
	SOURCE_LINK currentLink;
	currentLink = m_aLinksList.GetAt( nItemId );

	// Does the list need text information?
	if( pItem->mask & LVIF_TEXT )
	{
		TRACE( _T("SubItem = %d\n"), pItem->iSubItem );

		// set text
		CString szText;
		// set item id
		switch( pItem->iSubItem )		
		{
		case SOURCE_DATE:
			szText = currentLink.m_date_in.Format( appConfig.m_General.szDateFormat );
			break;
		case SOURCE_TITLE:
			szText = currentLink.m_title;
			break;
		case SOURCE_URL:
			szText = currentLink.m_link;
			break;
		}
		//Copy the text to the LV_ITEM structure
		//Maximum number of characters is in pItem->cchTextMax
		lstrcpyn( pItem->pszText, szText, pItem->cchTextMax );
	}

	// Does the list need image information?
	if( pItem->mask & LVIF_IMAGE ) 
	{
		TRACE( _T("IMAGE\n") );
		//// insert image
		//INT nImage = GetItemImage( nItemId, pItem->iSubItem );
		//// set image
		//if( nImage >= 0 )
		//	pItem->iImage = nImage;
	}

	// return
	*pResult = CDRF_DODEFAULT;
	*pResult = 0;
}

void CDlgListSource::OnHdnItemclickListLinks(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);

	HDITEM hdi;
	CHeaderCtrl *pHeader = m_ctrlLinksList.GetHeaderCtrl();
	ASSERT( pHeader );

	// toggle sort
	if( m_nCurrentSort == phdr->iItem )
		m_bSortAscending = !m_bSortAscending;
	else
	{
		// set sort type
		m_bSortAscending = TRUE;
		// set header information
		memset( &hdi, NULL, sizeof( HDITEM ));
		pHeader->GetItem( m_nCurrentSort, &hdi );
		hdi.mask |= HDI_FORMAT;
		hdi.fmt |= HDF_STRING;
		pHeader->SetItem( m_nCurrentSort, &hdi );
	}
	// set current sort
	m_nCurrentSort = phdr->iItem;

	// check for sort
	switch( m_nCurrentSort )
	{
	case SOURCE_DATE:
		m_szSort = _T("date_in");
		break;
	case SOURCE_TITLE:
		m_szSort = _T("title");
		break;
	case SOURCE_URL:
		m_szSort = _T("link");
		break;
	default:
		*pResult = 0;
		return;
	}

	// set sort type
	if( m_bSortAscending )
		m_szSort += _T(" ASC");
	else
		m_szSort += _T(" DESC");

	// set header information
	if( m_nCurrentSort >= 0 )
	{
		memset( &hdi, NULL, sizeof( HDITEM ));
		pHeader->GetItem( m_nCurrentSort, &hdi );
		hdi.mask |= HDI_FORMAT;
		if( m_bSortAscending )
			hdi.fmt |= HDF_STRING | HDF_SORTUP;
		else
			hdi.fmt |= HDF_STRING | HDF_SORTDOWN;
		pHeader->SetItem( m_nCurrentSort, &hdi );
	}

	// fill list
	FillList();

	*pResult = 0;
}

void CDlgListSource::OnLvnOdfinditemListLinks(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLVFINDITEM pFindInfo = reinterpret_cast<LPNMLVFINDITEM>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;
}

void CDlgListSource::OnNMDblclkListLinks(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	
    // Which item number?
    m_nCurrentRecord = pNMItemActivate->iItem;

	if( m_nCurrentRecord >= 0 )
	{
		// get request
		ASSERT( m_nCurrentRecord <= m_aLinksList.GetCount() );

		CDlgEditSource dlgSource;
		dlgSource.m_nStaffID = m_nStaffID;
		dlgSource.m_nItemID = m_aLinksList.GetAt( m_nCurrentRecord ).m_id;
		// show dialog
		if( dlgSource.DoModal() == IDOK )
		{
			// fill list
			FillList();
		}
	}	
	*pResult = 0;
}

INT CDlgListSource::SetDefaultButton(const DWORD nNewId) 
{
	DWORD nPrevId;

	nPrevId  = GetDefID();
	// Its not automatic - we have to remove the border from the old button
	SendDlgItemMessage(nPrevId, BM_SETSTYLE, BS_PUSHBUTTON, (LPARAM)TRUE);

	SetDefID(nNewId);
	// Likewise, add a border to the new one
	SendDlgItemMessage(nNewId, BM_SETSTYLE, BS_DEFPUSHBUTTON, (LPARAM)TRUE);

	return nPrevId;
}
